<?php

namespace app\common\service;

class UserAgentParserService extends ApiService
{
    /**
     * 解析 User-Agent 字符串
     *
     * @param string $userAgent User-Agent 字符串
     * @return array 解析结果
     */
    public function parse(string $userAgent): array
    {
        $result = [
            'browser' => [
                'name' => 'Unknown',
                'version' => 'Unknown'
            ],
            'os' => [
                'name' => 'Unknown',
                'version' => 'Unknown'
            ],
            'device' => [
                'type' => 'desktop',
                'model' => 'Unknown',
                'brand' => 'Unknown'
            ],
            'is_mobile' => false,
            'is_tablet' => false,
            'is_desktop' => true
        ];

        // 解析浏览器信息
        $result = $this->parseBrowser($userAgent, $result);

        // 解析操作系统信息
        $result = $this->parseOperatingSystem($userAgent, $result);

        // 解析设备信息
        $result = $this->parseDevice($userAgent, $result);

        return $result;
    }

    /**
     * 解析浏览器信息
     *
     * @param string $userAgent
     * @param array $result
     * @return array
     */
    protected function parseBrowser(string $userAgent, array $result): array
    {
        // Chrome 浏览器
        if (preg_match('/(?:Chrome|CriOS)\/([0-9\.]+)/i', $userAgent, $matches)) {
            $result['browser']['name'] = 'Chrome';
            $result['browser']['version'] = $matches[1];
        } // Firefox 浏览器
        elseif (preg_match('/Firefox\/([0-9\.]+)/i', $userAgent, $matches)) {
            $result['browser']['name'] = 'Firefox';
            $result['browser']['version'] = $matches[1];
        } // Safari 浏览器
        elseif (preg_match('/Safari\/([0-9\.]+)/i', $userAgent, $matches) &&
            !preg_match('/Chrome/i', $userAgent)) {
            $result['browser']['name'] = 'Safari';
            if (preg_match('/Version\/([0-9\.]+)/i', $userAgent, $versionMatches)) {
                $result['browser']['version'] = $versionMatches[1];
            }
        } // Edge 浏览器
        elseif (preg_match('/Edge\/([0-9\.]+)/i', $userAgent, $matches) ||
            preg_match('/Edg\/([0-9\.]+)/i', $userAgent, $matches)) {
            $result['browser']['name'] = 'Edge';
            $result['browser']['version'] = $matches[1];
        } // Opera 浏览器
        elseif (preg_match('/OPR\/([0-9\.]+)/i', $userAgent, $matches) ||
            preg_match('/Opera\/([0-9\.]+)/i', $userAgent, $matches)) {
            $result['browser']['name'] = 'Opera';
            $result['browser']['version'] = $matches[1];
        } // Internet Explorer
        elseif (preg_match('/MSIE\s([0-9\.]+)/i', $userAgent, $matches) ||
            preg_match('/Trident\/.*rv:([0-9\.]+)/i', $userAgent, $matches)) {
            $result['browser']['name'] = 'Internet Explorer';
            $result['browser']['version'] = $matches[1];
        }

        return $result;
    }

    /**
     * 解析操作系统信息
     *
     * @param string $userAgent
     * @param array $result
     * @return array
     */
    protected function parseOperatingSystem(string $userAgent, array $result): array
    {
        // Windows
        if (preg_match('/Windows\sNT\s([0-9\.]+)/i', $userAgent, $matches)) {
            $result['os']['name'] = 'Windows';
            $versionMap = [
                '10.0' => '10',
                '6.3' => '8.1',
                '6.2' => '8',
                '6.1' => '7',
                '6.0' => 'Vista',
                '5.1' => 'XP',
                '5.0' => '2000'
            ];
            $version = $matches[1];
            $result['os']['version'] = $versionMap[$version] ?? $version;
        } // macOS
        elseif (preg_match('/Mac\sOS\sX\s([0-9_]+)/i', $userAgent, $matches) ||
            preg_match('/Mac\sOS\sX/i', $userAgent)) {
            $result['os']['name'] = 'macOS';
            if (isset($matches[1])) {
                $result['os']['version'] = str_replace('_', '.', $matches[1]);
            }
        } // iOS
        elseif (preg_match('/iPhone|iPad|iPod/i', $userAgent)) {
            $result['os']['name'] = 'iOS';
            if (preg_match('/OS\s([0-9_]+)/i', $userAgent, $matches)) {
                $result['os']['version'] = str_replace('_', '.', $matches[1]);
            }
        } // Android
        elseif (preg_match('/Android\s([0-9\.]+)/i', $userAgent, $matches)) {
            $result['os']['name'] = 'Android';
            $result['os']['version'] = $matches[1];
        } // Linux
        elseif (preg_match('/Linux/i', $userAgent)) {
            $result['os']['name'] = 'Linux';
        }

        return $result;
    }

    /**
     * 解析设备信息
     *
     * @param string $userAgent
     * @param array $result
     * @return array
     */
    protected function parseDevice(string $userAgent, array $result): array
    {
        // 移动设备检测
        if (preg_match('/Mobile/i', $userAgent)) {
            $result['is_mobile'] = true;
            $result['is_desktop'] = false;
            $result['device']['type'] = 'mobile';
        }

        // 平板设备检测
        if (preg_match('/iPad|Tablet/i', $userAgent)) {
            $result['is_tablet'] = true;
            $result['is_mobile'] = false;
            $result['is_desktop'] = false;
            $result['device']['type'] = 'tablet';
        }

        // 设备品牌检测
        if (preg_match('/iPhone/i', $userAgent)) {
            $result['device']['brand'] = 'Apple';
            $result['device']['model'] = 'iPhone';
        } elseif (preg_match('/iPad/i', $userAgent)) {
            $result['device']['brand'] = 'Apple';
            $result['device']['model'] = 'iPad';
        } elseif (preg_match('/Android/i', $userAgent)) {
            $result['device']['brand'] = 'Android';
            if (preg_match('/;\s([^\)]+)\)/i', $userAgent, $matches)) {
                $result['device']['model'] = trim($matches[1]);
            }
        } elseif (preg_match('/Windows\sPhone/i', $userAgent)) {
            $result['device']['brand'] = 'Microsoft';
            $result['device']['model'] = 'Windows Phone';
        }

        return $result;
    }

    /**
     * 获取简化的浏览器信息
     *
     * @param string $userAgent
     * @return string
     */
    public function getBrowserName(string $userAgent): string
    {
        $parsed = $this->parse($userAgent);
        return $parsed['browser']['name'];
    }

    /**
     * 获取简化的操作系统信息
     *
     * @param string $userAgent
     * @return string
     */
    public function getOsName(string $userAgent): string
    {
        $parsed = $this->parse($userAgent);
        return $parsed['os']['name'];
    }

    /**
     * 检查是否为移动设备
     *
     * @param string $userAgent
     * @return bool
     */
    public function isMobile(string $userAgent): bool
    {
        $parsed = $this->parse($userAgent);
        return $parsed['is_mobile'];
    }
}
